package com.future.lock.pay;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.future.baselib.activity.BaseActivity;
import com.future.lock.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.Map;

/**
 * 继承并重写 success和fail方法即可
 * 支付宝使用为上半部分，使用时只需修改APPID和私钥RSA2_PRIVATE，如需对提示信息修改，请修改OrderInfoUtil
 * Created by jniu on 2017/5/31.
 */

public abstract class PayActivity extends BaseActivity implements IWXAPIEventHandler {

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String ALI_APPID = "2017122201065706";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCdRfcz+EELqTL2ucLOML4NTLS1/VaSv436fIFOROD1CF6F1P5jez0jR0DGDReel9musOqfn2ggTp8xa2dHqLsChW9R6Pc0DM/+/A15rbufrcmcyX0CDJArc9rUBQoGg6EQgslX7I31NbABzhTCp1BIyGE4haj8Cv1Mu6iK4Jj585WJ1CJ8cb+XzNV4Jd4jAK2AgWrWn6Bu4TB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+goLWk9HkEhArOlwWt66i8ICmmcDTLH1oBXjLXNJtlUNo3q2lGGMEkg3hKmZ2Xd/HijEjHYpPjV48f541bc6D70OooS6eaVUhEqo8t21f19RtOgVJPznQ+FSXGb3/R9vX5AoGBAM+8Zyvb2jIxL7Bk9OiN8Ucd4heeZ8Ja2lzHk3haJbhaxKV3N2OVyurwxf8LmnlypU9Hl10MVeQI8CtkBZw2keEXxBJdZBoHWXYMmtste0+43nfMYaeqOwMX8tueAbWtWxBGgFA2J7mCam55iIRxn9QxnNV+umAeDSO1H2cqnKmE";

    /**
     * 支付宝支付业务
     */
    public void payAli(double price, String subject, String orderSn) {
        if (TextUtils.isEmpty(ALI_APPID) || (TextUtils.isEmpty(RSA2_PRIVATE))) {
            Toast.makeText(this, "需要配置APPID | RSA_PRIVATE", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        String content = OrderInfoUtil.buildOrderContent(price, subject, orderSn);
        Map<String, String> params = OrderInfoUtil.buildOrderParamMap(ALI_APPID, content, rsa2);
        String orderParam = OrderInfoUtil.buildOrderParam(params);

        String privateKey = RSA2_PRIVATE;
        String sign = OrderInfoUtil.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked") PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            Log.e("payStatus", resultStatus);
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                paySuccess();
            }
            else if (TextUtils.equals(resultStatus, "4000")) {
                toast.show("订单支付失败");
            }
            else {
                payFail();
            }
        }
    };

    //TODO -----------------------------------------------------------------------------------------


    public void payWechat(JSONObject resultObject) {
        final IWXAPI api = getApi();
        if (api != null && resultObject != null) {
            PayReq request = new PayReq();
            WXPayEntryActivity.APP_ID = resultObject.optString("appid");
            request.appId = WXPayEntryActivity.APP_ID;
            request.partnerId = resultObject.optString("partnerid");
            request.prepayId = resultObject.optString("prepayid");
            request.packageValue = resultObject.optString("package");
            request.nonceStr = resultObject.optString("noncestr");
            request.timeStamp = resultObject.optString("timestamp");
            request.sign = resultObject.optString("sign");

            if (!api.registerApp(WXPayEntryActivity.APP_ID)) {
                toast("注册到微信失败!");
                return;
            }

            // 注册支付响应
            WXPayEntryActivity.setWXAPIEventHandler(this);

            // 发起支付请求
            api.sendReq(request);
        }
    }

    /**
     * 检查当前的api是否有效
     *
     * @return
     */
    protected IWXAPI getApi() {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(this, null);
        if (!iwxapi.isWXAppInstalled()) {
            toast("请先安装微信!");
            return null;
        }

        if (!iwxapi.isWXAppSupportAPI()) {
            toast("请先升级微信版本!");
            return null;
        }
        return iwxapi;
    }

    @Override
    public void onReq(BaseReq baseReq) {
        // not used
    }

    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp != null) {
            if (baseResp.errCode == 0) {
                paySuccess();
            }
            else {
                payFail();
            }
        }
    }

    /**
     * 支付成功回调
     */
    public abstract void paySuccess();

    /**
     * 支付失败回调
     */
    public abstract void payFail();

}
